import { Component } from 'react'
import { Provider, Consumer } from './data'

function GrandSon() {
  // 接收数据的方法
  const getData = (data) => {
    console.log('爷爷数据：', data)

    return (
      <div>
        <h1>{data.num}</h1>
        <button
          onClick={() => {
            data.changeCount(Math.random())
          }}>
          修改爷爷
        </button>
      </div>
    )
  }

  return (
    <div>
      <h3>孙子</h3>
      <hr />
      <div>
        <Consumer>{getData}</Consumer>
      </div>
    </div>
  )
}

function Son() {
  const getData = (data) => {
    console.log('儿子接收：', data)
  }
  return (
    <div>
      <h2>子</h2>
      <Consumer>{getData}</Consumer>
      <hr />
      <GrandSon />
    </div>
  )
}

class App extends Component {
  // 定义数据
  state = {
    count: 1000,
  }
  // 提供修改数据的方法
  changeCount = (data) => {
    this.setState({
      count: data,
    })
  }

  render() {
    return (
      // <Provider value={this.state.count}> => 共享了一个数据
      <Provider
        value={{ num: this.state.count, changeCount: this.changeCount }}>
        <div>
          <h1>父: {this.state.count}</h1>
          <hr />
          <Son />
        </div>
      </Provider>
    )
  }
}
export default App
